#include "etcd.hpp"
#include "channel.hpp"
#include <gflags/gflags.h>
#include <thread>
#include "speech_ser.hpp"
#include "baidu_aip_cpp/speech.h"

DEFINE_bool(run_mode, false, "程序运行模式 --false: 调试, --true: 发布");  
DEFINE_string(log_file, "./log.txt", "发布模式下, 指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下, 指定日志的输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控的根目录");
DEFINE_string(speech_service, "/service/speech", "服务监控的根目录");

int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    init(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    // 先构造RPC信道管理对象
    auto sm = std::make_shared<ServiceManager>();
    sm->declared(FLAGS_speech_service);
    auto put_cb = std::bind(&ServiceManager::onServiceOnline, sm.get(), std::placeholders::_1,
                            placeholders::_2);
    auto del_cb = std::bind(&ServiceManager::onServiceOnline, sm.get(), std::placeholders::_1,
                            placeholders::_2);

    // 构造服务发现对象
    Discovery::ptr dclient = std::make_shared<Discovery>(FLAGS_etcd_host, FLAGS_base_service,
                                                         put_cb, del_cb);

    // 发起speechPRPC调用
        // 通过RPC管理对象，获取提供speech服务的信道
        auto channel = sm->choose(FLAGS_speech_service);
        if (!channel)
        {
           std::cerr<<"RPC管理对象创建失败"<<std::endl;
            return -1;
        }
        ProtoAll::SpeechService_Stub stub(channel.get());
        ProtoAll:: SpeechServiceRequest req;
        std::string file_content;
        aip::get_file_content("../test/16k.pcm", &file_content);
        req.set_speech_content(file_content);
        brpc::Controller *cntl = new brpc::Controller();

        std::shared_ptr<ProtoAll::SpeechServiceResponce> rsp = std::make_shared<ProtoAll::SpeechServiceResponce>();
        stub.SpeechRecognition(cntl, &req, rsp.get(), nullptr);
        if (cntl->Failed() == true)
        {
            std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
            delete cntl;
            sleep(1);
            return -1;
        }
        std::cout << "收到响应: " << rsp->result() << std::endl;
        sleep(1);
    return 0;
}